package com.surekam.mnai.service.extractor.parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.surekam.mnai.dao.AddressDao;
import com.surekam.mnai.model.Address;
import com.surekam.mnai.model.MobileNumberAttribution;

/**
 *网址服务的解析 解析网址 http://www.iiip.com.cn/mobile/api.php?mobile=13901234567&api=testid2&utf=1
 *手机归属地API参数说明:
 *mobile——需查询的手机号码
 *api——返回数据将显示在此ID的对象中,在此处不起作用
 *utf——返回参数编码(1为utf-8,0为gb2312)
 *
 * @author caoxu
 */
public class IIIPParser implements IMobileNumberAttributionParser {
	private MobileNumberAttribution resultedObj = new MobileNumberAttribution();
	private String telephoneNo;
	
	@Autowired
	private AddressDao dao;
	
	public IIIPParser(String telephoneNo){
		this.telephoneNo = telephoneNo;
	}
	
	public IIIPParser(){
		
	}
	
	@Override
	public MobileNumberAttribution parse(InputStream is)
			throws ParseFailedException {
		byte datas[] = new byte[1024];
		String result ="" ;
		try {
			while(is.read(datas) != -1){
				result += new String(datas);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return getResultObject(result.trim());
	}
	
	/**
	 * 得到相关的解析结果
	 * @param result
	 * @return
	 */
	private MobileNumberAttribution getResultObject(String result) {
		Address address= getRelativeAddress(result);
		resultedObj.setAddress(address);
		resultedObj.setMobileNumberSegment(getTelephoneNo());
		resultedObj.setPhoneCardType("");
		resultedObj.setLastUpdatedTime(new Date());
		
		return resultedObj;
	}

	/**
	 * 得到相关的地址对象
	 * @param result
	 * @return
	 */
	private Address getRelativeAddress(String result){
		result = getProvinceAndCity(result);
		String province ="";
		String city ="";
		if(result.contains(" ")){
			int index = result.indexOf(" ");
			province = result.substring(0, index);
			city = result.substring(index);
			System.out.println(province + " " + city); //Debug
		} else {
			System.out.println(result);
			return dao.queryByProvince(result).get(0);
		}
		
		return dao.query(province, city);
	}
	
	private String getProvinceAndCity(String result) {
		int lastSingleQuote = result.lastIndexOf("'");
		int len = result.length();
		//得到倒数第二个单引号
		int lastSecondeSQ = result.substring(0, lastSingleQuote).
				lastIndexOf("'") + len - lastSingleQuote - 1;
		
		return result.substring(lastSecondeSQ, lastSingleQuote);
	}

	public String getTelephoneNo() {
		return telephoneNo;
	}
	
	/**
	 * 设置相对应的号码
	 * @param tele
	 */
	public void setTelephoneNo(String tele){
		this.telephoneNo = tele;
	}


}
